package com.changgou.pay.service.impl;

import com.changgou.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class WXPayServiceImpl implements WXPayService {

    @Autowired
    private WXPay wxPay;

    @Value("${wxpay.notify_url}")
    private String notify_url;

    @Override
    public Map nativePay(String orderId, Integer money)  {
        try {
            //按照微信支付的规范 封装参数
            Map<String,String> map = new HashMap<>();
            map.put("body","changgou");
            map.put("out_trade_no",orderId);

            BigDecimal payMoney =new BigDecimal("0.01");//元为单位
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));
            fen = fen.setScale(0,BigDecimal.ROUND_UP);//1分
//            map.put("total_fee",String.valueOf(money*100));
            map.put("total_fee",String.valueOf(fen));
            map.put("notify_url",notify_url);//回调地址
            map.put("trade_type","NATIVE");

            Map<String, String> result = wxPay.unifiedOrder(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Map queryOrder(String orderId) {

        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",orderId);

        try {
            Map<String, String> resultMap = wxPay.orderQuery(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Map closeOrder(String orderId) {

        Map<String, String> map =  new HashMap<>();
        map.put("out_trade_no",orderId);
        try {
            Map<String, String> resultMap = wxPay.closeOrder(map);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
